package com.xuanyue.db.xuan.antlr.v2.function;

import java.util.List;

import com.xuanyue.db.xuan.core.index.ListObject;
import com.xuanyue.db.xuan.core.table.IBitIndex;
import com.xuanyue.db.xuan.core.table.expr.Expr;
import com.xuanyue.db.xuan.core.table.expr.ExprValue;
import com.xuanyue.db.xuan.core.table.expr.ExprValueType;
import com.xuanyue.db.xuan.core.table.expr.IFunctionExecutor;

public class ListObjectMatchFunction implements IFunctionExecutor<ListObject<?>> {

	@Override
	public void exprExe(ListObject<?> column, ExprValue v, List<IBitIndex> caches) {
		List<ExprValue> evl = v.getValue();
		if(evl.size()!=column.getListSize()) {
			caches.get(0).setAll(false);
			return ;
		}
		Expr expr = new Expr();
		expr.setOp("=");
		int[] indexs = new int[] {0,0,0};
		expr.setArryIndex(indexs);
		ExprValue ev;
		IBitIndex r = caches.get(0);
		IBitIndex rTmp = caches.get(1);
		caches = caches.subList(1, caches.size());
		for(int i=0;i<evl.size();i++) {
			ev = evl.get(i);
			if(!ExprValueType.STRING.is(ev.getType())) {
				indexs[0]=i;
				expr.setValue(ev);
				column.exe(expr, caches);
				r.and(rTmp);
			}
		}
	}

	@Override
	public int exprCheck(ListObject<?> column, ExprValue v) {
		if(!ExprValueType.ARRAY.is(v.getType())) {
			return 0;
		}
		
		List<ExprValue> evl = v.getValue();
		Expr expr = new Expr();
		expr.setOp("=");
		expr.setArryIndex(new int[] {0,0,0});
		int s = 0;
		String mode = null;
		for(ExprValue ev:evl) {
			if(ExprValueType.STRING.is(ev.getType())) {
				mode = ev.getValue();
				if(!"_".equals(mode)) {
					return 0;
				}
			}else {
				expr.setValue(ev);
				s = column.checkAndContSource(expr);
				if(s==0) {
					return 0;
				}
			}
		}
		if(evl.size()!=column.getListSize()) {
			return 1;
		}
		return s+1;
	}
	

}
